package 网络编程.udp;

import 网络编程.Log;

import java.io.IOException;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class TranslateServer {
    //公开的IP和端口
    public final static int port = 9999;
    private static HashMap<String, String> map = new HashMap<>();
    static {
        map.put("apple","苹果");
        map.put("book","书");
        map.put("bicycle","自行车");
        Log.println("字典初始化完成");
    }

    public static void main(String[] args) throws Exception {
        Log.println("准备创建UDP Socklet ，端口是：" + port);
        DatagramSocket socket = new DatagramSocket(port);//参加Socket关键字
        Log.println("UDP Socket 创建完成");
        //服务器接受请求，被动接收，所以是一直处在运行态
        while (true){
            //1，参加Socket
            //参加容器接收数据,1024缓冲的大小
            byte[] buf = new byte[1024];
            //参加获取请求的数据包
            DatagramPacket receivePacket = new DatagramPacket(buf,buf.length);
            //获取从客户端发来的请求，如果客户端没有发送请求，就会一直再次阻塞

            //2,获取请求的信息
            Log.println("准备接收请求，容器大小" + buf.length);
            socket.receive(receivePacket);
            Log.println("接受到请求");
            //获取对方的IP和port
            InetAddress address = receivePacket.getAddress();
            int port1 = receivePacket.getPort();
            Log.println("请求方的端口 ： " + port1);
            Log.println("请求方的IP ： " + address);
            //获取对方的IP+port
            SocketAddress socketAddress = receivePacket.getSocketAddress();
            //获取请求内容
            byte[] data = receivePacket.getData();
            //获取接收数据的大小
            int length = receivePacket.getLength();
            Log.println("接收到请求的长度 ： " + length);
            //3，解析请求
            //字符集解码
            String request = new String(data,0,length,"UTF-8");
            String engWord = request;
            Log.println("接受到请求的数据为 ： " + engWord);

            //4,执行业务
            String chiWord = tranlaste(engWord);
            Log.println("翻译后的结果为： " + chiWord);
            //5，封装响应
            String response = chiWord;
            byte[] sendBuf = response.getBytes("UTF-8");
            //发送数据，要将接收方的信息一并封装到包中socketAddress
            DatagramPacket responsePacket = new DatagramPacket(sendBuf,0,sendBuf.length,socketAddress);
            Log.println("接收方发送响应 ... ");

            //6，发送响应
            socket.send(responsePacket);
            Log.println("接收方发送响应成功，发送的数据为 ： " + chiWord);
            //此时请求完成，等待下一次响应
        }
        //服务器关闭时，关闭所有的套接字资源
//        socket.close();
    }

    private static String tranlaste(String engWord) {
        String chiWord = map.getOrDefault(engWord,"查无此词");
        return chiWord;
    }
}
